<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 头部alert消息提示 -->
              <el-alert
                title="添加商品信息"
                type="info"
                :closable="false"
                show-icon
                center>
            </el-alert>
            <!-- 简单步骤条 -->
            <el-steps align-center :space="200" :active="activeIndex-0" finish-status="success">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- Tab栏切换区域 -->
            <!-- el-tabs里只能放el-tab-pane -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" :label-position="'top'">
                <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTableLeave" @tab-click="Tabclicked">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model.number="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model.number="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model.number="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                v-model="addForm.goods_cat"
                                :options="catelist"
                                :props="cascaderProps"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 数据要保存到el-form表单里去 -->
                        <!-- 循环渲染表单的Item项 -->
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="item1" :key="i1" v-for="(item1,i1) in item.attr_vals" border size="small"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            class="upload-demo"
                            :action="uploadURL"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :headers="headers"
                            list-type="picture"
                            :on-success="uploadSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器 -->
                        <quill-editor v-model="addForm.goods_introduce" @blur="onEditorBlur($event)"></quill-editor>
                        <el-button type="primary" class="addBtn" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览对话框 -->
        <el-dialog
            title="图片预览"
            :visible.sync="pireviewVisible"
            width="50%"
        >
        <img :src="previewPath" alt="">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'
    export default {
        data(){
            var validategoods_num = (rule, value, callback) => {
                var msg=''
                switch(rule.fullField){
                    case 'goods_price':
                        msg='商品价格'
                        break
                    case 'goods_weight':
                        msg='商品重量'
                        break
                    case 'goods_number':
                        msg='商品数量'
                        break
                }
                if (value === '') {
                callback(new Error(`请输入${msg}`));
                } else if(typeof value !=='number'){
                    callback(new Error(`${msg}必须是大于0的整数或小数`));
                }else if (value <0 ) {
                callback(new Error(`${msg}必须是大于0的整数或小数`));
                } else {
                callback();
                }
            }
            return {
                //进度条的步骤
                activeIndex: '0',
                //添加商品表单绑定的数据对象
                addForm:{
                    goods_name:'',
                    goods_price: '',
                    goods_weight: '',
                    goods_number: '',
                    //商品所属的分类数组
                    goods_cat:[],
                    //图片上传成功服务器返回的文件临时存放路径  
                    pics:[],
                    //商品详情描述
                    goods_introduce:'',
                    //存储静态参数与动态属性里的attr_id值和attr_vals值
                    attrs:[]
                },
                //表单的验证规则对象
                addFormRules:{
                    goods_name:[
                        {required:true,message:"商品名称不能为空",tigger:'blur'}
                    ],
                    goods_price:[
                        {required:true,message:"商品价格不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_weight:[
                        {required:true,message:"商品重量不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_number:[
                        {required:true,message:"商品数量不能为空"},
                        {validator:validategoods_num,tigger:'blur'}
                    ],
                    goods_cat:[
                        {required:true,message:'请选择商品分类'}
                    ]
                },
                //商品分类信息
                catelist:[],
                //级联配置选项
                cascaderProps:{
                    expandTrigger: 'hover',
                    label:'cat_name',
                    value:'cat_id',
                    children:'children'
                },
                //商品参数里的动态参数
                manyTableData:[],
                //静态属性
                onlyTableData:[],
                //图片上传的后台路径
                uploadURL:"http://127.0.0.1:8888/api/private/v1/upload",
                //上传图片用的请求头
                headers:{
                    Authorization:sessionStorage.getItem('token')
                },
                //预览图片存贮图片的
                previewPath:'',
                //图片预览对话框的显示与隐藏
                pireviewVisible:false
            }
        },
        created(){
            this.getCateList()
        },
        methods:{
            //获取所有商品分类数据
            async getCateList(){
                const {data:res}=await this.$http.get('categories')
                if(res.meta.status!==200) return this.$message.error('获取商品分类信息失败')
                this.catelist=res.data
                console.log(this.catelist);
            },
            //级联内容变化触发事件
            handleChange(){
                console.log(this.addForm.goods_cat);
                if(this.addForm.goods_cat.length!==3){
                    this.addForm.goods_cat=[]
                    this.$message.warning('只允许选择第三级分类')
                    return
                }
            },
            //选择tabs时触发    
            chooseTabs(){
                if(this.addForm.goods_cat.length!==3){
                    // this.activeIndex='0'
                }
                console.log(this.activeIndex);
            },
            //切换标签之前的钩子
            beforeTableLeave(activeName,oldActiveName){
                // console.log(oldActiveName);
                // console.log(activeName);
                // this.activeIndex='0'
                if(oldActiveName==='0'&&this.addForm.goods_cat.length!==3){
                    this.$message.error("请先选择商品分类")
                    return false
                }
            },  
            //Tab被选中之后触发
            async Tabclicked(){
                // console.log(this.activeIndex);
                // console.log(this.cateId);
                if(this.activeIndex==='1'){
                   const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:'many'}})
                    if(res.meta.status!==200) return this.$message.error('获取商品参数信息失败')
                    res.data.forEach(item=>{
                        item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
                    })
                    this.manyTableData=res.data
                    console.log(this.manyTableData);
                }else if(this.activeIndex==='2'){
                    const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:'only'}})
                    if(res.meta.status!==200) return this.$message.error('获取商品属性信息失败')
                    // res.data.forEach(item=>{
                    //     item.attr_vals=item.attr_vals?item.attr_vals.split(' '):[]
                    // })
                    this.onlyTableData=res.data
                    console.log(this.onlyTableData);
                }
            },
            //图片展示
            handlePreview(file){
                console.log(file);
                this.previewPath=file.response.data.url
                this.pireviewVisible=true
            },
            //关闭图片预览框
            handleRemove(file){
                console.log(file);
                // 1.获取将要删除图片的临时存放路径
                var removeFile=file.response.data.tmp_path
                // 2.从pics这个数组中，找到这个图片的索引值
                var i=this.addForm.pics.findIndex(item=>{
                    return removeFile===item.pic
                })
                // 3.调用splice方法，把图片信息对象从pics数组中删除
                this.addForm.pics.splice(i,1)
                console.log(this.addForm.pics);
            },
            //图片上传成功
            uploadSuccess(response){
                console.log(response);
                // 1.先拼接得到图片信息对象
                var picInfo={pic:response.data.tmp_path}
                //2.将图片信息对象push到addForm.pics中
                this.addForm.pics.push(picInfo)
                console.log(this.addForm);
            },
            //添加商品
            add(){
                console.log(this.addForm);
                this.$refs.addFormRef.validate(async valid=>{
                    if(!valid) return this.$message.error('请填写必要的表单参数')
                    console.log("验证通过添加商品吧");
                    //执行添加商品
                    //后台要求传goos_cat是字符串但是级联选择器却希望是数组
                    //需要采用插件lodash的deepClone复刻出新的对象提交不影响原对象
                    const form=_.cloneDeep(this.addForm)
                    form.goods_cat=form.goods_cat.join(',')
                    //动态参数处理
                    this.manyTableData.forEach(item=>{
                        const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
                        this.addForm.attrs.push(newInfo)
                    })
                    //静态属性处理
                    this.onlyTableData.forEach(item=>{
                        const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
                        this.addForm.attrs.push(newInfo)
                    })
                    form.attrs=this.addForm.attrs
                    console.log(form);
                    //发起添加请求
                    //商品名称必须唯一
                    const {data:res}=await this.$http.post('goods',form)
                    if(res.meta.status!==201) return this.$message.error('添加商品失败')
                    this.$message.success('添加商品成功')
                    this.$router.push('/goods')
                })
            },
            //富文本失去焦点
            onEditorBlur(e){
                this.addForm.goods_introduce=e.container.innerText
                console.log(this.addForm.goods_introduce);
                console.log(e);
            }
        },
        computed:{
            cateId(){
                if(this.addForm.goods_cat.length===3){
                    return this.addForm.goods_cat[2]
                }
                return null
            }
        }
    }
</script>

<style lang="less" scoped>
    .el-cascader{
        width: 250px;
    }
    .el-checkbox{
        margin: 0 15px 0 0!important;
    }
    .el-dialog img{
        width: 100%;
    }
    .addBtn{
        margin-top: 15px;
    }
</style>